package com.mar.quarkus.login;

import com.mar.quarkus.constants.DelFlag;
import com.mar.quarkus.jwt.model.UserModel;
import com.mar.quarkus.jwt.spi.BaseUserModelProvider;
import com.mar.quarkus.model.SysRoleModel;
import com.mar.quarkus.model.SysUserModel;

import javax.enterprise.context.ApplicationScoped;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;

/**
 * Description: 实现用户认证SPI .<br>
 *
 * @author m-xy
 *     Created By 2020/4/23 11:13
 */
@ApplicationScoped
public class LoginUserProvider extends BaseUserModelProvider {
    private final static String SQL_USER_ROLE = "select distinct r from SysRoleModel r inner join SysUserRoleModel ur "
        + " on r.id = ur.roleId where ur.userId = ?1";

    @Override
    public UserModel getUserByUserName(String userName) {
        Optional<SysUserModel> sysUserModels = SysUserModel.find(
            "userName = ?1 and delFlag = ?2",
            userName,
            DelFlag.LIVE.getCode()
        ).firstResultOptional();
        if (!sysUserModels.isPresent()) {
            return null;
        }
        SysUserModel sysUserModel = sysUserModels.get();
        UserModel userModel = new UserModel();
        userModel.setUserId(String.valueOf(sysUserModel.id));
        userModel.setUserName(sysUserModel.userName);
        userModel.setPassword(sysUserModel.password);
        userModel.setRoles(new HashSet<String>());
        List<SysRoleModel> roleModels = SysRoleModel.find(
            SQL_USER_ROLE, sysUserModel.id).list();
        roleModels.forEach(sysRoleModel -> {
            userModel.getRoles().add(sysRoleModel.roleKey);
        });
        return userModel;
    }
}
